package com.maduar.mybatis.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.maduar.mybatis.demo.OpratorEnum;
import com.maduar.mybatis.demo.mapper.UserMapper;
import com.maduar.mybatis.demo.mapstruct.PageMapper;
import com.maduar.mybatis.demo.service.strategy.MathInteface;
import com.maduar.mybatis.demo.service.strategy.MathSubImpl;
import com.maduar.mybatis.demo.util.DemoUtils;
import com.maduar.mybatis.demo.vo.PageResultRet;
import com.maduar.mybatis.demo.vo.UserPageRes;
import com.maduar.mybatis.demo.vo.UserPageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * Description:
 *
 * @author maduar maduar@163.com
 * @date 2021-04-11 00:08
 */
@Service
public class UserService {

    public static Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper mapper;

    @Autowired
    private PageMapper pageMapper;

    @Autowired
    @Qualifier("sub")
    private MathInteface mathSub;

    @Autowired
    @Qualifier("add")
    private MathInteface mathAdd;

    public PageResultRet<UserPageRes> listPageUser(UserPageVo pageVo) {
        if (Objects.isNull(pageVo)) {
            logger.error("listPageUser:  pageVo is null");
            throw new RuntimeException("pageVo is null");
        }

        IPage<UserPageRes> iPage = listPageUserCommon(pageVo);

        return pageMapper.userPageToRes(iPage);
    }

    public IPage<UserPageRes> listPageUserCommon(UserPageVo pageVo) {
        QueryWrapper<UserPageRes> q = new QueryWrapper<>();
        q.orderByAsc("age");

        String name = pageVo.getName();
        if (!StringUtils.isEmpty(name)) {
            q.like("A.name", name);
        }

        String email = pageVo.getEmail();
        if (!StringUtils.isEmpty(email)) {
            q.like("A.email", email);
        }

        return mapper.pageSelect(DemoUtils.getPage(pageVo), q);
    }

    public Integer exec(Integer a, Integer b, Integer operat) {
        OpratorEnum opratorEnum = OpratorEnum.getByCode(operat);
        if (Objects.isNull(opratorEnum)) {
            return 0;
        }

        return operat(a, b, opratorEnum);
    }

    private Integer operat(Integer a, Integer b, OpratorEnum opratorEnum) {
        Integer code = opratorEnum.getCode();
        int result = 0;
        switch (code) {
            case 1:
                result = mathAdd.exec(a, b);
                break;
            case 2:
                result = mathSub.exec(a, b);
                break;
            default:
                return 0;
        }

        return result;
    }
}
